<?php

class Model {

	private $table;
	private $db;

	public function __construct($table, $db) {
		$this->table = $table;
		$this->db = $db;
	}

	public function query($offset = 0, $limit = 0) {
		$sql = "SELECT * FROM {$this->table}";

		if($limit)
			$sql .= " LIMIT {$offset},{$limit};";

		return $this->db->query($sql);
	}

	public function insert($data) {
		foreach ($data as $key => $value) {
			$data[$key] = addslashes($value);
		}

		$keys = implode('\',\'', array_keys($data));
		$values = implode('\',\'', array_values($data));

		$sql = "insert into {$this->table}('{$keys}') values ('{$values}')";

		return $this->db->exec($sql);
	}

	public function update($data) {
		$id = $data['id'];
		unset($data['id']);
		$sqlData = array();
		foreach ($data as $key => $value) {
			$value = addslashes($value);
			array_push($sqlData, "'{$key}'='{$value}'");
		}

		$sql = "update {$this->table} set " . implode(',', $sqlData) . " where id='{$id}'";

		return $this->db->exec($sql);
	}

	public function find($id) {
		$sql = "select * from {$this->table} where id='{$id}' limit 1";
		$data = $this->db->query($sql);
		return isset($data[0]) ? $data[0] : false;
	}

	public function delete($id) {
		$sql = "delete from {$this->table} where id='{$id}'";

		return $this->db->exec($sql);
	}

	public function __destroy() {
		unset($this->db);
	}

}